"use strict";

const Controller = require("egg").Controller;

/**
 * @controller 前端API
 */
class WebApiController extends Controller {
  /**
   * @summary 博客分页查询
   * @router post /api/web/blogIndex
   * @request body BlogIndexQuery 博客首页查询
   */
  async indexPage() {
    const { ctx } = this;
    const query = ctx.request.body;
    query.pageNum = parseInt(query.pageNum);
    query.pageSize = parseInt(query.pageSize);
    const blogList = await ctx.service.blog.index(query);
    const total = await ctx.model.Blog.count();
    ctx.body = {
      code: 200,
      msg: "获取博客列表",
      data: { total, blogList },
    };
  }

  /**
   * @summary 博客详情
   * @router get /api/web/blogs/{blogId}
   * @request path number blogId 博客Id
   */
  async blogShow() {
    const { ctx } = this;
    const blogId = ctx.params.blogId;
    const blog = await ctx.model.Blog.findByPk(blogId);
    ctx.body = {
      code: blog ? 200 : 404,
      msg: "获取博客详情",
      data: { blog },
    };
  }

  /**
   * @summary 查询所有博客，按分类分组
   * @router get /api/web/getBlogsGroupByCategory
   */
  async getBlogsGroupByCategory() {
    const ctx = this.ctx;
    const blogs = await ctx.service.blog.getBlogsGroupByCategory();
    ctx.body = {
      code: 200,
      msg: "查询所有博客，按分类分组",
      data: blogs,
    };
  }

  /**
   * @summary 查询某个分类下的博客
   * @router get /api/web/getBlogsByCategoryId
   * @request query number categoryId 分类id
   */
  async getBlogsByCategoryId() {
    const ctx = this.ctx;
    const categoryId = ctx.query.categoryId;
    ctx.body = {
      code: 200,
      msg: "查询某个分类下的博客",
      data: await ctx.service.blog.getBlogsByCategoryId(categoryId),
    };
  }

  /**
   * @summary 查询所有分类
   * @router get /api/web/category
   */
  async getAllCategory() {
    const { ctx } = this;
    ctx.body = {
      code: 200,
      msg: "查询所有分类",
      data: await ctx.model.Category.findAll(),
    };
  }

  /**
   * @summary 根据分类id查询分类信息
   * @router get /api/web/category/{categoryId}
   * @request path number categoryId 分类id
   */
  async getCategoryById() {
    const ctx = this.ctx;
    const categoryId = ctx.params.categoryId;
    console.log(categoryId);
    const category = await ctx.model.Category.findByPk(categoryId);
    ctx.body = {
      code: 200,
      msg: "根据分类id查询分类信息",
      data: category,
    };
  }

  /**
   * @summary 获取博客数和标签数
   * @router get /api/web/getBlogAndTagNum
   */
  async getBlogAndTagNum() {
    const ctx = this.ctx;
    ctx.body = {
      code: 200,
      msg: "获取博客数和标签数",
      data: {
        blogNum: await ctx.model.Blog.count(),
        tagNum: await ctx.model.Tag.count(),
      },
    };
  }
}

module.exports = WebApiController;
